package EnterpriseAlgorithm.Stack_Queue.Code.StackWithGetMin;

class MyStack1 {
    private final java.util.Stack<Integer> stackData;
    private final java.util.Stack<Integer> stackMin;
    public MyStack1() {
        this.stackData = new java.util.Stack<Integer>();
        this.stackMin = new java.util.Stack<Integer>();
    }
    public void push(int newNum) {
        if (this.stackMin.isEmpty()) {  //stackMin为空直接压入，作为当前最小
            this.stackMin.push(newNum);
        } else if (newNum <= this.getMin()) {// newNum <= stackMin.peek()时，就要让newNum也压入getMain
            this.stackMin.push(newNum);
        }
        this.stackData.push(newNum); // 元素是一定要stackData
    }
    public int pop() {
        if (this.stackData.isEmpty()) {
            throw new RuntimeException("Your stack is empty.");
        }
        int value = this.stackData.pop();  // 出栈操作，要注意出栈的元素是否为栈内最小。
        if (value == this.getMin()) {
            this.stackMin.pop();  // 栈的元素若为栈内最小，则应与stackData一样将其弹出栈
        }
        return value;
    }
    public int getMin() {
        if (this.stackMin.isEmpty()) {
            throw new RuntimeException("Your stack is empty.");
        }
        return this.stackMin.peek(); // getMin 栈顶元素保存目前栈内元素最小值
    }
}
